<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-button type="primary" :icon="Refresh" @click="loadData">刷新</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户昵称">
          <el-input
            v-model="searchForm.nickname"
            placeholder="请输入用户昵称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="searchForm.role" placeholder="全部角色" clearable>
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon admin">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.admins }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon user">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.users }}</div>
            <div class="stat-label">普通用户</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总计</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
      >
        <el-table-column type="index" label="#" width="60" />

        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info-cell">
              <el-avatar :size="40" :src="row.avatarUrl || undefined">
                {{ row.nickname?.[0] || '?' }}
              </el-avatar>
              <div class="user-text">
                <div class="nickname">{{ row.nickname || '匿名用户' }}</div>
                <el-text type="info" size="small">ID: {{ row.id }}</el-text>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="row.role === 'ADMIN' ? 'danger' : 'primary'" size="small">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="username" label="用户名" min-width="150">
          <template #default="{ row }">
            <el-text v-if="row.username">{{ row.username }}</el-text>
            <el-text v-else type="info" size="small">未设置</el-text>
          </template>
        </el-table-column>

        <el-table-column label="OpenID" min-width="200">
          <template #default="{ row }">
            <el-text type="info" size="small" style="word-break: break-all">
              {{ row.openid }}
            </el-text>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="注册时间" min-width="180" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                size="small"
                :icon="View"
                @click="handleView(row)"
              >
                详情
              </el-button>
              <el-button
                v-if="row.role !== 'ADMIN'"
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-tooltip v-else content="管理员账号无法删除" placement="top">
                <el-button type="danger" size="small" :icon="Delete" disabled>
                  删除
                </el-button>
              </el-tooltip>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="700px"
      destroy-on-close
    >
      <el-descriptions v-if="currentUser" :column="2" border>
        <el-descriptions-item label="用户ID">
          {{ currentUser.id }}
        </el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="currentUser.role === 'ADMIN' ? 'danger' : 'primary'">
            {{ getRoleText(currentUser.role) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户头像" :span="2">
          <el-avatar :size="60" :src="currentUser.avatarUrl || undefined">
            {{ currentUser.nickname?.[0] || '?' }}
          </el-avatar>
        </el-descriptions-item>
        <el-descriptions-item label="昵称">
          {{ currentUser.nickname || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ currentUser.username || '未设置' }}
        </el-descriptions-item>
        <el-descriptions-item label="OpenID" :span="2">
          <el-text type="info" size="small" style="word-break: break-all">
            {{ currentUser.openid }}
          </el-text>
        </el-descriptions-item>
        <el-descriptions-item label="UnionID" :span="2">
          <el-text v-if="currentUser.unionid" type="info" size="small" style="word-break: break-all">
            {{ currentUser.unionid }}
          </el-text>
          <el-text v-else type="info" size="small">未设置</el-text>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间" :span="2">
          {{ formatDateTime(currentUser.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">
          {{ formatDateTime(currentUser.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Search,
  View,
  Delete,
  UserFilled,
  User,
  Avatar
} from '@element-plus/icons-vue'
import { getUsers, deleteUser } from '@/api/user'
import type { User as UserType, UserRole } from '@/types/api'

// 数据状态
const loading = ref(false)
const tableData = ref<UserType[]>([])
const currentUser = ref<UserType | null>(null)
const detailDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  nickname: '',
  role: ''
})

// 分页
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 统计数据
const stats = computed(() => {
  const admins = tableData.value.filter((item) => item.role === 'ADMIN').length
  const users = tableData.value.filter((item) => item.role === 'USER').length
  return {
    admins,
    users,
    total: pagination.total
  }
})

/**
 * 加载数据
 */
async function loadData() {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }

    if (searchForm.role) {
      params.role = searchForm.role as UserRole
    }

    const response = await getUsers(params)

    if (response.success) {
      // 过滤搜索条件
      let filteredData = response.data
      if (searchForm.nickname) {
        filteredData = filteredData.filter((item) =>
          item.nickname?.toLowerCase().includes(searchForm.nickname.toLowerCase())
        )
      }

      tableData.value = filteredData
      pagination.total = response.pagination.total
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
function handleSearch() {
  pagination.page = 1
  loadData()
}

/**
 * 重置搜索
 */
function handleReset() {
  searchForm.nickname = ''
  searchForm.role = ''
  pagination.page = 1
  loadData()
}

/**
 * 查看详情
 */
function handleView(user: UserType) {
  currentUser.value = user
  detailDialogVisible.value = true
}

/**
 * 删除
 */
async function handleDelete(user: UserType) {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${user.nickname || '匿名用户'}"吗？删除后将无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    loading.value = true
    const response = await deleteUser(user.id)

    if (response.success) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 页码改变
 */
function handlePageChange(page: number) {
  pagination.page = page
  loadData()
}

/**
 * 每页数量改变
 */
function handleSizeChange(size: number) {
  pagination.limit = size
  pagination.page = 1
  loadData()
}

/**
 * 获取角色文本
 */
function getRoleText(role: UserRole) {
  const textMap = {
    ADMIN: '管理员',
    USER: '普通用户'
  }
  return textMap[role] || role
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateString: string) {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  background: transparent;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.admin {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: #fff;
}

.stat-icon.user {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格样式 */
.user-info-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-text {
  flex: 1;
}

.nickname {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
